<template>
  <div>
    <div>


      <!-- 基本信息 -->
      <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;">
        <div class="blue_item" />
        <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">基础信息</span>
        <van-button v-show="canChooseSJ" block type="info" style="display: inline-block;width:auto;height: 33px;"
          native-type="button" @click="pushSJTableView()">选择关联项目</van-button>
      </div>

      <div>
        <van-field readonly required name="initiator" v-model="fromdata.initiator" label="发起人：" label-width="4em" />
        <van-field readonly required name="initiatorCall" v-model="fromdata.initiatorCall" label="发起人电话："
          label-width="6em" />
        <van-field readonly required name="initiatorTime" v-model="fromdata.initiatorTime" label="发起时间："
          label-width="5em" />
        <van-field readonly required name="projectName" v-model="fromdata.projectName" label="项目名称："
          label-width="5em" />
        <van-field readonly required name="projectID" v-model="fromdata.projectID" label="项目编码：" label-width="5em" />
        <van-field readonly required name="businessName" v-model="fromdata.businessName" label="商机名称："
          label-width="5em" />
        <van-field readonly required name="businessId" v-model="fromdata.businessId" label="商机编码：" label-width="5em" />
        <van-field readonly required name="city" v-model="fromdata.city" label="地市：" label-width="3em" />
        <van-field readonly required name="counties" v-model="fromdata.counties" label="县区：" label-width="3em" />
      </div>


      <!-- <div class="spline"></div> -->
      <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;">
        <div class="blue_item" />
        <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">变更决策信息</span>
        <van-button v-show="canChooseSJ" block type="info" style="display: inline-block;width:auto;height: 33px;"
          native-type="button" @click="pushHYJYTableView()">选择关联会议纪要</van-button>
      </div>
      
      <div>
        <van-field readonly required name="changeReason" v-model="fromdata.changeReason" label="项目变更原因："
          label-width="7em" :right-icon="canChooseSJ ? 'arrow' : ''" @click="changeReasonShowPopop = canChooseSJ"
          :rules="[{ required: canChooseSJ, message: '请选择项目变更原因' }]" />
        <van-popup v-model="changeReasonShowPopop" position="bottom" get-container="body">
          <van-picker show-toolbar value-key="value" :columns="changeReasonColumns" @confirm="changeReasonClickConfirm"
            @cancel="changeReasonShowPopop = false">
          </van-picker>
        </van-popup>

        <van-field readonly required name="changeSummaryCode" v-model="fromdata.changeSummaryCode" label="变更决策会议纪要编码："
          label-width="11em" :rules="[{ required: canChooseSJ, message: '请选择变更决策会议纪要编码' }]" />
        <van-field readonly required name="changeSummaryName" v-model="fromdata.changeSummaryName" label="变更决策会议纪要名称："
          label-width="11em" :rules="[{ required: canChooseSJ, message: '请选择变更决策会议纪要名称' }]" />

        <van-field readonly required name="changeOpenDate" v-model="fromdata.changeOpenDate" label="变更决策通过日期："
          label-width="9em" :right-icon="canChooseSJ ? 'arrow' : ''" @click="changeOpenDateShowPopup = canChooseSJ"
          :rules="[{ required: canChooseSJ, message: '请选择变更决策通过日期' }]" />
        <van-popup v-model="changeOpenDateShowPopup" position="bottom" get-container="body">
          <van-datetime-picker v-model="currentDate" :formatter="formatter" type="date" @confirm="changeOpenDateComfirm"
            @cancel="changeOpenDateShowPopup = false"></van-datetime-picker>
        </van-popup>


        <div>
          <van-field readonly required label="变更决策文件：" label-width="7em"
            :rules="[{ required: canChooseSJ && (fromdata.changeDecisionFileList === undefined || fromdata.changeDecisionFileList === null || fromdata.changeDecisionFileList.length === 0), message: '请上传变更决策文件' }]">
            <template #button v-if="canChooseSJ">
              <van-uploader name="changeDecisionFileList" :after-read="didFinishPickingFiles">
                <van-button native-type="button" size="small" icon="plus" type="primary">上传附件</van-button>
              </van-uploader>
            </template>
          </van-field>

          <div v-for="(fileitem, index) in fromdata.changeDecisionFileList" :key="fileitem.id" style="margin-left:20px">
            <div readonly class="font14 fileLink" style="color:#0F85CF">
              <a target="_blank" @click="openFileUrlfun(fileitem.anonymousFilePath)">{{ fileitem.fileName
                }}</a>
            </div>

            <van-icon v-if="canChooseSJ" name="close" color="#ea0023" size="20"
              @click="deleteFile('changeDecisionFileList', index)"></van-icon>
          </div>
        </div>



        <div>
          <van-field readonly label="其他材料：" label-width="5em">
            <template #button v-if="canChooseSJ">
              <van-uploader name="otherFileList" :after-read="didFinishPickingFiles">
                <van-button native-type="button" size="small" icon="plus" type="primary">上传附件</van-button>
              </van-uploader>
            </template>
          </van-field>

          <div v-for="(fileitem, index) in fromdata.otherFileList" :key="fileitem.id" style="margin-left:20px">
            <div readonly class="font14 fileLink" style="color:#0F85CF">
              <a target="_blank" @click="openFileUrlfun(fileitem.anonymousFilePath)">{{ fileitem.fileName
                }}</a>
            </div>

            <van-icon v-if="canChooseSJ" name="close" color="#ea0023" size="20"
              @click="deleteFile('otherFileList', index)"></van-icon>
          </div>
        </div>



        <van-field :readonly='!canChooseSJ' maxlength="500" autosize type="textarea" rows="1" name="remark"
          v-model="fromdata.remark" label="备注：" label-width="3em" />
      </div>

      <section-header v-if="showCBMoudle" :sectionTitle="'变更审批意见'"></section-header>
      <div v-if="showCBMoudle">

        <van-field readonly required name="changeAdvice" v-model="fromdata.changeAdvice" label="变更审批意见："
          label-width="7em" />
        <van-field readonly required name="changeDate" v-model="fromdata.changeDate" label="变更审批时间："
          label-width="7em" />
      </div>

      <historyAndSuggs v-if="showOpinionMoudle" id='target' :showHistory='showHistoryMoudle' :historydata='historydata'
        :approveList='approveList' />

      <!-- 底部占位 -->
      <div style="padding-bottom: 42px"></div>

    </div>
  </div>
</template>

<script>



import { openFileUrl } from '@/store/openFile'
import historyAndSuggs from "@/views/srqr/historyAndSuggs.vue"
import jDrawupUtil, { ChooseSJ_KEY, DrawupChooseType_SJ, dict_xmbg_code, DrawupChooseType_HYJY, Choose_HYJY_KEY } from '../../assets/js/dict_process_helper';
import { mapGetters } from "vuex"
import SectionHeader from '../sztdzj/sztdzjDetail/section-header.vue';
import moment from 'moment';
import { uploadFileCommon } from '../../api/dictapi';
import { Dialog } from 'vant';

export default {
  data() {
    return {


      changeReasonShowPopop: false,
      changeReasonColumns: [{ value: '项目变更' }, { value: '项目延期' }],

      changeOpenDateShowPopup: false,
      currentDate: new Date(),


    }
  },

  computed: {

    ...mapGetters(['user']),
    ...mapGetters(['userinfo']),

    canChooseSJ() {

      return this.pushParams.isDrawup == '1' || this.pushParams.location == 'dict.start';
    },





    showCBMoudle() {

      if (this.pushParams.location == 'dict.startToDirecto' ||
        this.pushParams.location == 'dict.AdminToGiveMaster' ||
        this.pushParams.location == 'dict.SpecialDirecToAdmin' ||
        this.pushParams.location == 'dict.start') {
        return false;
      }
      else {
        return true
      }
    },

    /// 意见
    showOpinionMoudle() {
      return this.pushParams.isDrawup != '1';
    },

    showHistoryMoudle() {
      return this.pushParams.todoType == "2" && this.historydata.MANAGER && this.pushParams.isDrawup != '1';
    },
  },

  activated() {

    if (this.canChooseSJ) {

      if (localStorage.getItem(Choose_HYJY_KEY) != '{}' &&
        localStorage.getItem(Choose_HYJY_KEY)) {

        let hyjyInfo = JSON.parse(localStorage.getItem(Choose_HYJY_KEY));
        localStorage.setItem(Choose_HYJY_KEY, '{}')

        this.fromdata.changeSummaryCode = hyjyInfo.zihao;
        this.fromdata.changeSummaryName = hyjyInfo.title;
      }
    }


  },

  props: ['pushParams', 'fromdata', 'historydata', 'approveList'],
  methods: {


    // 跳转商机界面 关联商机信息
    pushSJTableView() {

      /// 去往 中转 商机列表
      this.pushParams.transType = DrawupChooseType_SJ;
      this.pushParams.processID = dict_xmbg_code;
      this.$router.push(
        {
          name: 'drawup_transition_tab',
          query: this.pushParams,
        }
      )
    },

    // 跳转商机中转界面 关联会议纪要信息
    pushHYJYTableView() {

      /// 去往 中转 会议纪要列表
      this.pushParams.transType = DrawupChooseType_HYJY;
      this.pushParams.processID = dict_xmbg_code;
      this.$router.push(
        {
          name: 'drawup_transition_tab',
          query: this.pushParams,
        }
      )
    },

    tomsg() {
      document.getElementById('target').scrollIntoView({ behavior: 'smooth' })
    },

    openFileUrlfun(value) {
      this.$router.push(
        {
          name: 'fileview',
          query: {
            openFileUrl: openFileUrl(value)
          }
        }
      );
    },

    changeReasonClickConfirm(value) {

      console.log(value);
      this.changeReasonShowPopop = false;
      this.fromdata.changeReason = value.value;
    },

    /// 年月日 时间格式
    formatter(type, val) {
      if (type === 'year') {
        return `${val}年`;
      }
      else if (type === 'month') {
        return `${val}月`;
      }
      else if (type === 'day') {
        return `${val}日`;
      }

      return val;
    },

    changeOpenDateComfirm(value) {

      this.changeOpenDateShowPopup = false;

      let changeOpenDate = moment(value).format('YYYY-MM-DD');
      this.currentDate = changeOpenDate;
      this.fromdata.changeOpenDate = changeOpenDate;
    },

    /// 本地文件选中后的回调
    didFinishPickingFiles(file, detail) {
      console.log('照片上传', detail.name, this.fromdata[detail.type]);

      let fileData = new FormData();
      fileData.append("pmInsType", this.pmInsType);
      fileData.append("pmInsTypePart", "1");
      fileData.append("files", file.file);

      let params = new Map();
      params.pmInsType = this.pmInsType;
      params.pmInsTypePart = '1';
      params.userName = this.user.userName;
      uploadFileCommon(fileData, params).then((res) => {
        if (!res.data) {
          Notify(res.message);
          return;
        }
        if (res.data.data) {
          this.showUploadFiles(res.data.data, detail.name);
        }
      });
    },


    // 上传附近后的 回显
    showUploadFiles(fileData, key) {

      if (this.fromdata[key] === null ||
        this.fromdata[key] === undefined) {
        this.fromdata[key] = [];
      }

      console.log('照片回显', key, this.fromdata[key]);
      this.fromdata[key].push(fileData.sysFiles[0]);
      this.$forceUpdate(); // 强制刷新界面
    },

    deleteFile(key, index) {
      Dialog.confirm({ title: "提示", message: "是否删除此附件？" })
        .then(() => {
          this.fromdata[key].splice(index, 1);
          this.$forceUpdate(); // 强制刷新界面
        })
        .catch(() => { });
    },


  },
  components: {
    historyAndSuggs,
    SectionHeader
  },
}
</script>

<style>
.tables.el-table .cell {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  line-height: 15px;
  padding-left: 5px;
  padding-right: 5px;
}
</style>